package com.stone.framework.common.log.service.impl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Optional;
import java.util.stream.IntStream;

import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import com.stone.framework.common.client.BasicClient;
import com.stone.framework.common.log.entity.Span;
import com.stone.framework.common.log.service.SysLogService;
import com.stone.framework.message.common.log.SysLogPageReqBody;
import com.stone.framework.message.common.log.SysLogPageResBody;

@Service
public class SysLogServiceImpl implements SysLogService {

    private static final String PREFIX_INDEX = "zipkin:span-";

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private BasicClient basicClient;

    public Page<SysLogPageResBody> queryPage(SysLogPageReqBody reqBody, Pageable pageable) {
        String days = Optional.ofNullable(basicClient.getValue("common.log.days")).orElse("30");
        Map<String, String> map = basicClient.getKV("common.log.urls");

        String[] indices = this.buildIndices(PREFIX_INDEX, Integer.parseInt(days));
        MatchQueryBuilder queryBuilder = QueryBuilders.termQuery("", value);

        SearchQuery searchQuery =
            new NativeSearchQueryBuilder().withIndices(indices).withQuery(queryBuilder).withPageable(pageable).build();
        elasticsearchTemplate.queryForPage(searchQuery, Span.class);
        return null;
    }

    private String[] buildIndices(String prefix, int days) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
        LocalDate date = LocalDate.now();
        return IntStream.range(0, days).mapToObj(i -> date.minusDays(i).format(formatter)).toArray(String[]::new);
    }

}
